package com.ccp.dev.system.listener;

import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.system.license.SysLicense;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 监听session创建和失效事件。
 * @author y
 *
 */
@Component
public class UserSessionListener extends SysLicense implements HttpSessionListener {

	protected Logger logger = LoggerFactory.getLogger(UserSessionListener.class);

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		String sessionId = arg0.getSession().getId();
		SessionRegistry sessionRegistry = AppUtil.getBean(SessionRegistry.class);
		SysUserService sysUserService = AppUtil.getBean(SysUserService.class);
		SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
		if(null != sessionInformation){
			SysUser sysUser = (SysUser)sessionInformation.getPrincipal();
			sysUserService.logoutSuccessSet(sysUser.getUserId());
			sessionRegistry.removeSessionInformation(sessionId);
		}
	}
}
